<?php

namespace app\api\controller;

use app\admin\model\Lines;
use app\common\controller\Api;
use app\common\library\RedisService;
use app\common\model\Config;

/**
 * create by PhpStorm 2025/9/27 15:00
 * bus.com app\api\controller@Equipment
 * 行止之行 <xingzhi8711@gmail.com>
 * 设备接口
 */
class Equipment extends Api
{
    protected $noNeedLogin=['*'];
    protected $noNeedRight=['*'];
    public function init()
    {
        $code=$this->request->request("code");
        $station=$this->request->request("station");
        $list=\app\admin\model\Equipment::where('code',$code)->whereOr('station',$station)->find();
        if($list){
            $this->error('设备或站点已被关联过不要重复关联');
        }
        $equipment=\app\admin\model\Equipment::create([
            'code'=>$code,
            'station'=>$station,
            'name'=>$station."的站牌",
        ]);
        $this->success('ok',$equipment);
    }
    public function getLinesList_back()
    {
        $station=$this->request->request("station");
        $redis=new RedisService();
        $allLines=$redis->hgetAll("station_".$station);
        $list=array();
        foreach ($allLines as $key => $value){
            $timeTable=json_decode(Lines::where('id',$key)->value('timetable'),true);
            $len=count($timeTable);
            if($len>1){
                $name=$timeTable[0]['station']."-".$timeTable[$len-1]['station'];
                $name_en=$timeTable[0]['station_en']."-".$timeTable[$len-1]['station_en'];
            }else{
                $name=$timeTable[0]['station'];
                $name_en=$timeTable[0]['station_en'];
            }
            $option=[$value,$key,$name,$name_en];
            $fRes=$this->formatTime($option);
            $list=array_merge($list,$fRes);
        }
        $equipment=\app\admin\model\Equipment::where('station',$station)->find();
    
        array_multisort($list, SORT_ASC,array_column($list, 'left'));
        $redis->set("equipment_".$station."_last_request",time());
        $this->success('ok',['list'=>$list,'equipment'=>$equipment]);
    }
    public function formatTime($option)
    {
        list($data,$lines_id,$name,$name_en)=$option;
        $where=[
            'lines_id'=>$lines_id,
            'start_time'=>['<',date("H:i")],
            'end_time'=>['>',date("H:i")],
        ];
        $bus=\app\admin\model\Bus::where($where)
            ->select();
        $return=array();
        $redis=new RedisService();
        $transList=$redis->get("en_ch_list");
        $transList=json_decode($transList,true);
        $transData=array();
        foreach ($transList as $key => $value){
            $key=$value['key'];
            $transData[$key]=$value;
        }
        if($bus){
            foreach ($bus as $key => $value){
                $times=time()-strtotime(date("Y-m-d")." ".$value['start_time']);
                if($times<$data['run_times']){
                    $diff_time=$data['run_times']-$times;
                    if($diff_time<60){
                        $zh=$transData[1]['zh'];
                        $en=$transData[1]['en'];
                    }else{
                        $zh=str_replace("#min#",floor(($diff_time)/60),$transData[2]['zh']);
                        $en=str_replace("#min#",floor(($diff_time)/60),$transData[2]['en']);
                    }
                    $return[]=[
                        "left"=>$diff_time,
                        "f_lef"=>$zh,
                        "f_lef_en"=>$en,
                        'name'=>$name,
                        'name_en'=>$name_en,
                        'station_data'=>$data
                    ];
                }elseif($times<$data['run_times']+$data['stop_times']){
                    $return[]=[
                        "left"=>'0',
                        "f_lef"=>$transData[3]['zh'],
                        "f_lef_en"=>$transData[3]['en'],
                        'name'=>$name,
                        'name_en'=>$name_en,
                        'station_data'=>$data
                    ];
                }
            }
        }else{
            $return[]=[
                "left"=>0,
                "f_lef"=>$transData[4]['zh'],
                "f_lef_en"=>$transData[4]['en'],
                'name'=>$name,
                'name_en'=>$name_en,
                'station_data'=>$data
            ];
        }


        return $return;
    }
    
    
     /**
     * 根据站点名称获取所有经过线路的到站时间和发车时间
     */
    public function getLinesList()
    {
        $stationName=$this->request->request("station");
        
        if (!$stationName) {
            $this->error('请输入站点名称');
        }
        
        // 1. 获取经过该站点的所有线路
        $stationLines = \app\admin\model\BusStation::where('station_name', $stationName)
                                 ->select();
        
        if (!$stationLines) {
            $this->error('该站点暂无线路经过');
        }
        
        $result = [];
        
        // 2. 对每条线路计算到站时间和下一趟发车时间
        foreach ($stationLines as $station) {
            $lineId = $station['line_id'];
            
            // 获取线路信息
            $line = \app\admin\model\BusLine::find($lineId);
            if (!$line) {
                continue;
            }
            
            // 获取下一趟发车时间
            $nextDeparture = $this->getNextDepartureTime($lineId);
            
            // 获取到站时间
            $arrivalInfo = $this->getArrivalTime($lineId, $stationName);
            $result = [];
            if( $nextDeparture && $arrivalInfo ){
                $result[] = [
                    'line_info' => [
                        'line_id' => $line['id'],
                        'line_number' => $line['line_number'],
                        'line_name' => $line['line_name'],
                        'direction' => $line['direction'],
                        'start_station' => $line['start_station'],
                        'end_station' => $line['end_station'],
                        'station_order' => $station['station_order']
                    ],
                    'next_departure' => $nextDeparture,
                    'arrival_info' => $arrivalInfo
                ];
            }
        }
        if( !$result ){
            $this->error('暂无最新班次信息！');
        }
        $this->success('ok',$result);
    }
    
    /**
     * 获取下一趟发车时间（优化班次逻辑）
     */
    private function getNextDepartureTime($lineId)
    {
        $currentTime = date('H:i:s');
        $currentWeekday = date('N'); // 1-7 周一到周日
        
        // 获取今天所有符合条件的班次
        $schedules = \app\admin\model\BusSchedule::where('line_id', $lineId)
                              ->where(function($query) use ($currentWeekday) {
                                  // 周一到周五的班次 (1-5)
                                  if ($currentWeekday >= 1 && $currentWeekday <= 5) {
                                      $query->whereOr('weekdays', '1-5');
                                  }
                                  // 周一到周六的班次 (1-6)
                                  if ($currentWeekday >= 1 && $currentWeekday <= 6) {
                                      $query->whereOr('weekdays', '1-6');
                                  }
                                  // 每天的班次 (1-7)
                                  $query->whereOr('weekdays', '1-7');
                                  // 特定周几的班次
                                  $query->whereOr('weekdays', 'like', '%' . $currentWeekday . '%');
                              })
                              ->where('departure_time', '>', $currentTime)
                              ->order('departure_time', 'asc')
                              ->select();
        
        if ($schedules) {
            $nextSchedule = $schedules[0];
            return [
                'departure_time' => $nextSchedule['departure_time'],
                'remaining_minutes' => $this->calculateTimeDiff($currentTime, $nextSchedule['departure_time']),
                'weekdays' => $nextSchedule['weekdays'],
                'schedule_type' => $nextSchedule['schedule_type']
            ];
        }
        
        // 如果今天没有后续班次，返回明天第一班
        $tomorrowWeekday = $currentWeekday == 7 ? 1 : $currentWeekday + 1;
        $tomorrowSchedules = \app\admin\model\BusSchedule::where('line_id', $lineId)
                                       ->where(function($query) use ($tomorrowWeekday) {
                                           // 周一到周五的班次 (1-5)
                                           if ($tomorrowWeekday >= 1 && $tomorrowWeekday <= 5) {
                                               $query->whereOr('weekdays', '1-5');
                                           }
                                           // 周一到周六的班次 (1-6)
                                           if ($tomorrowWeekday >= 1 && $tomorrowWeekday <= 6) {
                                               $query->whereOr('weekdays', '1-6');
                                           }
                                           // 每天的班次 (1-7)
                                           $query->whereOr('weekdays', '1-7');
                                           // 特定周几的班次
                                           $query->whereOr('weekdays', 'like', '%' . $tomorrowWeekday . '%');
                                       })
                                       ->order('departure_time', 'asc')
                                       ->select();
        
        if ($tomorrowSchedules) {
            $firstSchedule = $tomorrowSchedules[0];
            return [
                'departure_time' => $firstSchedule['departure_time'],
                'remaining_minutes' => '明日首班',
                'is_tomorrow' => true,
                'weekdays' => $firstSchedule['weekdays'],
                'schedule_type' => $firstSchedule['schedule_type']
            ];
        }
        
        return null;
    }
    
    /**
     * 获取到站时间（基于预设时间计算）
     */
    private function getArrivalTime($lineId, $stationName)
    {
        // 获取站点信息
        $station = \app\admin\model\BusStation::where('line_id', $lineId)
                           ->where('station_name', $stationName)
                           ->find();
        
        if (!$station) {
            return null;
        }
        
        $currentTime = date('H:i:s');
        $currentWeekday = date('N');
        
        // 查找最近已发车的班次
        $latestSchedules = \app\admin\model\BusSchedule::where('line_id', $lineId)
                                     ->where(function($query) use ($currentWeekday) {
                                         // 周一到周五的班次 (1-5)
                                         if ($currentWeekday >= 1 && $currentWeekday <= 5) {
                                             $query->whereOr('weekdays', '1-5');
                                         }
                                         // 周一到周六的班次 (1-6)
                                         if ($currentWeekday >= 1 && $currentWeekday <= 6) {
                                             $query->whereOr('weekdays', '1-6');
                                         }
                                         // 每天的班次 (1-7)
                                         $query->whereOr('weekdays', '1-7');
                                         // 特定周几的班次
                                         $query->whereOr('weekdays', 'like', '%' . $currentWeekday . '%');
                                     })
                                     ->where('departure_time', '<=', $currentTime)
                                     ->order('departure_time', 'desc')
                                     ->select();
        
        if ($latestSchedules) {
            $latestSchedule = $latestSchedules[0];
            
            // 计算预计到达时间
            $departureTimestamp = strtotime(date('Y-m-d') . ' ' . $latestSchedule['departure_time']);
            $estimatedArrivalTimestamp = $departureTimestamp + ($station['estimated_minutes'] * 60);
            $currentTimestamp = time();
            
            $remainingSeconds = $estimatedArrivalTimestamp - $currentTimestamp;
            
            // 如果车辆已经过站，返回0
            if ($remainingSeconds < 0) {
                $remainingSeconds = 0;
            }
            
            return [
                'data_source' => 'preset',
                'estimated_arrival_seconds' => $remainingSeconds,
                'estimated_arrival_minutes' => ceil($remainingSeconds / 60),
                'departure_time' => $latestSchedule['departure_time'],
                'station_order' => $station['station_order'],
                'schedule_type' => $latestSchedule['schedule_type']
            ];
        }
        
        return null;
    }
    
    /**
     * 计算时间差（分钟）
     */
    private function calculateTimeDiff($startTime, $endTime)
    {
        $start = strtotime($startTime);
        $end = strtotime($endTime);
        $diff = round(($end - $start) / 60);
        return $diff > 0 ? $diff : 0;
    }
}